#pragma  once

#include <iostream>
#include <string>
#include <vector>
#include <sstream>
#include <unordered_map>
#include <fstream>
#include "Common.hpp"
#include "Log.hpp"

const std::string Sep = "\r\n";
const std::string LineSep = " ";
const std::string HeaderLineSep = ": ";
const std::string BlankLine = Sep;
const std::string defaulthomepage = "wwwroot";
const std::string http_version = "HTTP/1.0";
const std::string page404 = "wwwroot/404.html";
const std::string firstpage = "index.html";

using namespace LogModule;

class HttpReauest
{
public:
    HttpReauest() {}

    ~HttpReauest() {}

    bool IsHasArgs()
    {
        return _isexec;
    }

    bool ParseHeaderKv()
    {
        std::string key, value;
        for(auto &herder : _req_header)
        {
            if(SplitString(herder, HeaderLineSep, &key, &value))
            {
                _headerkv.push_back(std::make_pair(key, value));
            }
        }
        return true;
    }

    bool ParseHeader(std::string &request_str)
    {
        std::string line;
        while(true)
        {
            bool r = ParseOneLine(request_str, &line, Sep);
            if(r && !line.empty())
            {
                _req_header.push_back(line);
            }
            else if(r && line.empty())
            {
                _blank_line = Sep;
                break;
            }
            else 
            {
                return false;
            }
        }
        ParseHeaderKv();

        // 查找 cookie 
        std::string prefix = "Cookie: ";    // 写入：Set-Cookie: sessionid=1234   提交: Cookie: sessionid=1234
        for(auto &line : _req_header)
        {
            std::string cookie;
            if(strncmp(line.c_str(), prefix.c_str(), prefix.size()) == 0)
            {
                cookie = line.substr(prefix.size());   // 截取 Cookie之后的就可以了
                _cookies.emplace_back(cookie);
                break;
            }
        }

        // 查找sessionid
        prefix = "sessionid=";
        for(auto &cookie : _cookies)
        {
            if(strncmp(cookie.c_str(), prefix.c_str(), prefix.size()) == 0)
            {
                _sessionid = cookie.substr(prefix.size());
            }
        }

        return true;
    }

    void Deserialize(std::string &request_str)
    {
        if(ParseOneLine(request_str, &_req_line, Sep))
        {
            // 提取请求行中的详细字段
            ParseReqLine(_req_line, LineSep);
            ParseHeader(request_str); // 解析报头
            _body = request_str;

            // 分析请求中是否含有参数
            if(_method == "POST")
            {
                _isexec = true;  // 参数在正文
                _path = _uri;
                _args = _body;
            }
            else if(_method  == "GET")
            {
                auto pos = _uri.rfind('?');
                if(pos != std::string::npos)
                {
                    _isexec = true;
                    //  /login?name=zhangsan&passwd=123456
                    _path = _uri.substr(0, pos);
                    _args = _uri.substr(pos + 1);
                } 
            }
        }
    }

    std::string GetContent(const std::string &path)
    {
        // 二进制读
        std::string content;
        std::ifstream in(path, std::ios::binary);
        if(!in.is_open()) return std::string();
        in.seekg(0, in.end);
        int filesize = in.tellg();
        in.seekg(0, in.beg);

        content.resize(filesize);
        in.read((char*)content.c_str(), filesize);
        in.close();
        LOG(LogLevel::DEBUG) << "content length: " << content.size();
        return content;

        // 暂时做法
        // std::string content;
        // std::ifstream in(_uri);
        // if(!in.is_open()) return std::string();
        // std::string line;
        // while(getline(in, line))
        // {
        //     content += line;
        // }
        // in.close();
        // return content;
    }

    void Print()
    {
        std::cout << "_method: " << _method << std::endl;
        std::cout << "_uri: " << _uri << std::endl;
        std::cout << "_version: " << _version << std::endl;

        for(auto &kv : _headerkv)
        {
            std::cout << kv.first << " # " << kv.second << std::endl;
        }
        std::cout << "_blank_line: " << _blank_line << std::endl;

        std::cout << "_body: " << _body << std::endl;
    }

    std::string Uri()
    {
        return _uri;
    }

    void SetUri(const std::string &newuri)
    {
        _uri = newuri;
    }

    std::string Path() { return _path; }
    std::string Args() { return _args; }
    std::string SessionId() { return _sessionid; } 
    bool Islog() { return _sessionid.size() != 0; }

    std::string Suffix()
    {
        auto pos = _uri.rfind(".");
        if(pos == std::string::npos) return std::string(".html");
        else return _uri.substr(pos);
    }
private:
    void ParseReqLine(const std::string &_req_line, const std::string &LineSep)  // 请求行字段解析 
    {
        (void)LineSep;
        std::stringstream ss(_req_line);
        ss >> _method >> _uri >> _version;
    }

private:
    std::string _req_line;
    std::vector<std::string> _req_header;
    std::string _blank_line;
    std::string _body;

    // 在反序列化的过程中，细化我们解析出来的字段
    std::string _method;
    std::string _uri;      // 用户想要这个
    std::string _path;
    std::string _args;
    std::string _version;
    std::vector<std::pair<std::string, std::string>> _headerkv;
    std::vector<std::string> _cookies;
    std::string _sessionid;
    bool _isexec = false;
};

// 对于http请求，都要有应答
class HttpResponse
{
public:
    HttpResponse() : _version(http_version), _blank_line(Sep)
    {}

    void Build(HttpReauest &req)
    {
        std::string uri = defaulthomepage + req.Uri();
        if(uri.back() == '/')
        {
            uri += firstpage;
            // req.SetUri(uri);
        }

        _content = req.GetContent(uri);
        if(_content.empty()) 
        {
            // 用户请求的资源并不存在
            _status_code = 404;
            _content = req.GetContent(page404);
        }
        else 
        {
            _status_code = 200;
        }
        LOG(LogLevel::DEBUG) << "客户端在请求：" << req.Uri();
        _status_desc = Code2Desc(_status_code);     // 和状态码是强相关的

        if(!_content.empty())
        {
            SetHeader("Content-Length", std::to_string(_content.size()));

            std::string mime_type = Suffix2Desc(req.Suffix());
            SetHeader("Content-Type", mime_type);
        }
        _body = _content;
    }

    void SetCode(int code) 
    {
        _status_code = code;
        _status_desc = Code2Desc(_status_code);
    }

    void SetBody(const std::string &body)
    {
        _body = body;
    }

    void SetHeader(const std::string &k, const std::string &v)
    {
        _header_kv.push_back(std::make_pair(k, v));
    }

    void Serialize(std::string *resp_str)
    {
        for(auto &header : _header_kv)
        {
            _resp_header.push_back(header.first + HeaderLineSep + header.second);
        }

        _resp_line = _version + LineSep + std::to_string(_status_code) + LineSep + _status_desc + Sep;   // 第一行

        // 序列化
        *resp_str = _resp_line;
        for(auto &line : _resp_header)
        {
            *resp_str += (line + Sep);
        }
        *resp_str += _blank_line;
        *resp_str += _body;
    }

    ~HttpResponse() {}
private:
    std::string Code2Desc(int code)
    {
        switch (code)
        {
        case 200:
            return "OK";
        case 404:
            return "Not Found";
        case 301:
            return "Move Permanently";
        case 302:
            return "Found";
        default:
            return std::string();
        }
    }

    std::string Suffix2Desc(const std::string &suffix)
    {
        if(suffix == ".html")
            return "text/html";
        else if(suffix == ".jpg")
            return "application/x-jpg";
        else 
            return "text/html";
    }
private:
    // 必备的要素
    std::string _version;
    int _status_code;
    std::string _status_desc;
    std::string _content;
    std::vector<std::pair<std::string, std::string>> _header_kv;

    // 最终要这4部分，构建应答
    std::string _resp_line;
    std::vector<std::string> _resp_header;
    std::string _blank_line;
    std::string _body;
};